<template>
  <div class="container">
    <!-- 头部导航 -->
    <div>
      <van-nav-bar fixed>
        <template v-slot:left>
          <img src="@/assets/logo.png" alt="" class="logo" />
        </template>
        <template #right>
          <van-icon name="search" size="0.48rem" color="#fff" @click="moveSearchPageFn"></van-icon>
        </template>
      </van-nav-bar>
    </div>
    <!-- tab栏导航 -->
    <div class="main">
      <van-tabs v-model="channelId" animated sticky offset-top="1.226667rem" @change="channelChangeFn" >
        <van-tab v-for="item in userChannelList" :key="item.id" :title="item.name" :name="item.id">
          <ArticleList :channelId="channelId"></ArticleList>
        </van-tab>
      </van-tabs>

      <!-- 编辑频道图标 -->
      <van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="plusClickFn" />
    </div>

    <!-- 频道管理弹出层 -->
    <van-popup class="channel_popup" v-model="show" get-container="body">
      <ChannelEdit :userList="userChannelList" :unCheckList="unCheckChannelList" @addChannelEV="addChannelFN" @removeChannelEV="removeChannelFn" @closeEV="closeFn" ref="editRef" v-model="channelId"></ChannelEdit>
    </van-popup>
  </div>
</template>
<script>
import { getUserChannelsAPI, getAllChannelsAPI, updateChannelsAPI, removeTheChannelAPI } from '@/api'
import ArticleList from './components/ArticleList.vue'
import ChannelEdit from './ChannelEdit.vue'
import Notify from '@/ui/Notify'
export default {
  name: 'MyHome',
  data () {
    return {
      channelId: 0, // tab导航-激活频道的ID
      userChannelList: [], // 用户选择的频道列表
      allChannelList: [], // 所有频道的列表
      // articleList: [] // 文章列表
      show: false, // 频道弹出层显示或隐藏
      channelScrollTObj: {} // 保存每个频道滚动位置
    }
  },
  components: {
    ArticleList,
    ChannelEdit
  },
  methods: {
    // tabs切换的事件
    channelChangeFn () {
    //   // 获取文章列表
    //   const res2 = await getAllArticleListAPI({ channel_id: this.channelId, timestamp: (new Date()).getTime() })
    //   console.log(res2)
    //   this.articleList = res2.data.data.results

      // tab切换，设置滚动条的位置
      // 切回来的一瞬间，没有高度，滚动事件从地下上来也被触发了，所以才把数据里设置为0
      // 切回来的一瞬间，高度为0，所以设置滚动位置也没用
      this.$nextTick(() => {
        document.documentElement.scrollTop = this.channelScrollTObj[this.channelId]
        document.body.scrollTop = this.channelScrollTObj[this.channelId]
        console.log(222)
      })
    },

    // +号点击方法
    plusClickFn () {
      this.show = true
    },
    // 添加频道
    async addChannelFN (channelObj) {
      this.userChannelList.push(channelObj)
      // 把数据发送给后台
      // 因为后台需要的数据和我们定义的数据不一样，还需要对数组进行操作才能和后台的数组一样
      const newArr = this.userChannelList.filter(obj => obj.id !== 0)
      const theNewArr = newArr.map((obj, index) => {
        const newObj = { ...obj } // 拷贝（浅拷贝）
        delete newObj.name
        newObj.seq = index

        return newObj // 让map方法把新对象收集起来，形成一个新的数组
      })
      // 发起请求
      await updateChannelsAPI({ channels: theNewArr })
    },
    // 删除频道
    async removeChannelFn (channelObj) {
      const index = this.userChannelList.findIndex(obj => obj.id === channelObj.id)
      this.userChannelList.splice(index, 1)

      // 调用删除接口
      const res = await removeTheChannelAPI({ channelId: channelObj.id })
      if (res.status === 204) {
        Notify({ type: 'success', message: '删除成功' })
      } else {
        Notify({ type: 'warning', message: '删除失败' })
      }
    },
    // 关闭弹出层
    closeFn () {
      this.show = false
      this.$refs.editRef.edit = false
    },
    // 首页-右上角放大镜点击事件 -> 跳转搜索页面
    moveSearchPageFn () {
      this.$router.push('/search')
    },
    // 封装获取轮动距离的函数 -> 监听网页滚动时间
    scrollFn () {
      this.$route.meta.scrollT = document.documentElement.scrollTop || document.body.scrollTop
      this.channelScrollTObj[this.channelId] = document.documentElement.scrollTop || document.body.scrollTop
      console.log(this.channelScrollTObj)
      console.log(111)
    }
  },
  computed: {
    unCheckChannelList () {
    //   // 目标：把所有频道数组挨个对象取出，去用户已选频道数组里查找，如果找不到，则让filter方法收集到一个新数组里
    //   const newArr = this.allChannelList.filter(bigObj => {
    //     const index = this.userChannelList.findIndex(smallObj => {
    //       return smallObj.id === bigObj.id
    //     })

      //     // 如果找到了
      //     if (index > -1) {
      //       return false
      //     } else { return true }
      //   })

      //   return newArr
      // }

      // 简化写法
      return this.allChannelList.filter(bigObj => (this.userChannelList.findIndex(smallObj => smallObj.id === bigObj.id) === -1))
    }

  },
  async created () {
    const res = await getUserChannelsAPI()
    // console.log(res)
    this.userChannelList = res.data.data.channels

    // 调用获取文章列表方法
    // this.channelChangeFn()

    // 所有频道列表
    const res2 = await getAllChannelsAPI()
    this.allChannelList = res2.data.data.channels
  },
  // 无缓存，切走后调用destroted声明函数，加了<keep-alive></keep-alive>切走后调用deactiveed函数（a'c't）
  activated () {
    window.addEventListener('scroll', this.scrollFn)
    document.documentElement.scrollTop = this.$route.meta.scrollT
    document.body.scrollTop = this.$route.meta.scrollT
  },
  deactivated () {
    window.removeEventListener('scroll', this.scrollFn)
  }
}
</script>
<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
.main {
  padding-top: 46px;
}

// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}

.channel_popup {
  // vw和vh是css3新出的单位，参考的是百分比    是可视窗口百分比
  width: 100vw;
  height: 100vh;
}
</style>
